import 'dart:math';
import 'dart:ui' as ui;

import 'package:flame/components/animation_component.dart';
import 'package:flame/components/component.dart';
import 'package:flame/components/composed_component.dart';
import 'package:flame/components/mixins/has_game_ref.dart';
import 'package:flame/components/mixins/resizable.dart';
import 'package:flame/components/mixins/tapable.dart';
import 'package:flame/sprite.dart';
import 'package:flutter/cupertino.dart';
import 'package:fluttergame/config.dart';
import 'package:fluttergame/util.dart';

class Obstacle extends PositionComponent
  with HasGameRef, Tapable, ComposedComponent, Resizable {

  final ui.Image spriteImage;
  ui.Size size;
  ObstacleChild firstComponent;
  ObstacleChild secondComponent;
  Obstacle(this.spriteImage, this.size){
    firstComponent = ObstacleChild(spriteImage, size, y);
    print('h:${firstComponent.height}');
    secondComponent = ObstacleChild(spriteImage, size, y)..x=size.width;
    this..add(firstComponent)..add(secondComponent);
    secondComponent.refresh();
  }

  @override
  void update(double t) {}

  void updateWithSpeed(double t, double speed){
    double x =  t * 1 * speed;
    for(final c in components){
      final component = c as PositionComponent;
      print(component.width);
      if(component.x + size.width < 0){
        if(component == firstComponent){
          firstComponent.x = secondComponent.x + secondComponent.width;
          firstComponent.refresh();
        }else{
          secondComponent.x = firstComponent.x + firstComponent.width;
          secondComponent.refresh();
        }
      }
      component.x -= x;
      component.update(t);
    }
  }

}
class ObstacleChild extends PositionComponent
  with HasGameRef, Tapable, ComposedComponent, Resizable {
  ui.Size size;
  ui.Image spriteImage;
  double maxY;
  ObstacleChild(this.spriteImage, this.size, this.maxY);

  PositionComponent createComponent(double x){
    ObstacleConfig config = ObstacleConfig.list[Random().nextInt(3)];
    final Sprite sprite = Sprite.fromImage(spriteImage,
      width: config.w,
      height: config.h,
      y: config.y,
      x: config.x
    );
    return SpriteComponent.fromSprite(config.w, config.h, sprite)
      ..x=x..y=size.height - (HorizonConfig.h + config.h - 22);
  }

  @override
  void update(double t) {
    for(final c in components){
      final component = c as PositionComponent;
      component.x = x+component.x;
    }
  }

  void refresh(){
    components.clear();
    double x = 0;
    while(true){
      if(x>=size.width){
        return;
      }
      x += getRandomNum(210, 600);
      PositionComponent component = createComponent(x+this.x);
      x += component.width;
      add(component);
    }
  }
}